
const opts = {
  width: 100, // canvas size
  height: 100,
  top: 20, // 左上角
  left: 20,
  right: 20, // 相对于canvas右下角的位置 // default: top - ruleOptions.top
  bottom: 20,
  w: 4, // 纵向的宽度
  h: 4, // 横向的高度
  fillColor: 'blue',
  isTexure: false, // 是否填充纹理
  texture: 'imgurl'
}

function setOuterFrame(ctx, options) {
  const { width, height, top, left, right, bottom, w, h, fillColor, isTexure, texure } = options

  ctx.save()

  if (!isTexure) { // 填充颜色
    ctx.fillStyle = fillColor || '#fff'
    ctx.fillRect(left, top, width - (left + right), h) // top
    ctx.fillRect(left, height - bottom - h, width - (left + right), h) // bottom
    ctx.fillRect(left, top, w, height - (top + bottom)) // left
    ctx.fillRect(width - right - w, top, w, height - (top + bottom)) // right

    ctx.restore()
  } else {
    const img = new Image()
    const texure_width = 45
    const texure_height = 45
    const texure_w = 15
    const texure_h = 15

    img.onload = function() {
      const outer_width = width - (left + right) // 外框的宽度
      const outer_height = height - (top + bottom) - 2 * texure_h // 外框 中间部分 的高度

      const n = Math.floor(outer_width / texure_width)
      const ys = Math.floor(outer_width % texure_width) // 余数
      // const percent = ys / texure_width // 余数占的百分比

      for (let i = 0; i < n; i++) {
        ctx.drawImage(img, 0, 0, texure_width, texure_h, left + i * texure_width, top, texure_width, texure_h) // top
        ctx.drawImage(img, 0, texure_height - texure_h, texure_width, texure_h, left + i * texure_width, height - bottom - texure_h, texure_width, texure_h) // bottom

        if (i === n - 1) {
          ctx.drawImage(img, 0, 0, ys, texure_h, left + n * texure_width, top, ys, texure_h) // top
          ctx.drawImage(img, 0, texure_height - texure_h, ys, texure_h, left + n * texure_width, height - bottom - texure_h, ys, texure_h) // bottom
        }
      }

      const col_h = texure_height - 2 * texure_h // 纹理 中间部分 的高度
      const m = Math.floor(outer_height / col_h)
      const ys_m = Math.floor(outer_height % col_h) // 余数

      for (let i = 0; i < m; i++) {
        ctx.drawImage(img, 0, texure_h, texure_w, col_h, left, top + texure_h + i * col_h, texure_w, col_h) // left
        ctx.drawImage(img, texure_width - texure_w, texure_h, texure_w, col_h, width - right - texure_w, top + texure_h + i * col_h, texure_w, col_h) // right

        if (i === m - 1) {
          ctx.drawImage(img, 0, texure_h, texure_w, ys_m, left, top + texure_h + m * col_h, texure_w, ys_m) // left
          ctx.drawImage(img, texure_width - texure_w, texure_h, texure_w, ys_m, width - right - texure_w, top + texure_h + m * col_h, texure_w, ys_m) // right
        }
      }
    }

    img.src = texure
  }
}

export { setOuterFrame }

